//
//  VVYSaveDataManager.m
//  viviyoo
//
//  Created by viviyoo on 15/10/27.
//  Copyright © 2015年 viviyoo. All rights reserved.
//

#import "VVYSaveDataManager.h"




NSString *const KEY_USERID = @"KEY_USERID";
NSString *const KEY_PHONE = @"KEY_PHONE";
NSString *const KEY_USERNAME = @"KEY_USERNAME";
NSString *const KEY_USERMESSAGE = @"KEY_USERMESSAGE";

static FMDatabase *_db;

@implementation VVYSaveDataManager



/**
 *  获取单个文件大小
 */
- (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
/**
 * 获取文件夹大小
 */

- (float ) folderSizeAtPath:(NSString*) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString* fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
    }
    
    return folderSize/(1024.0*1024.0);
    
}

/**
 *  拿到数据库
 */
+(void)initialize{
    
    //1.获得数据库文件的路径
    NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *fileName=[doc stringByAppendingPathComponent:@"student.sqlite"];
    
    //2.获得数据库
    FMDatabase *db=[FMDatabase databaseWithPath:fileName];
    
    [db open];
    
    _db=db;
    
}



/**
 *  创建表
 */
+ (void)createTableWithName:(NSString *)tableName andKeyTypes:(NSDictionary *)keyTypes{
    
    if ([_db open]) {
        
        //        NSString *dropStr = [NSString stringWithFormat:@"DROP TABLE IF EXISTS %@;",tableName];
        
        //        [_db executeUpdate:dropStr];
        
        NSMutableString *sql = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (",tableName]];
        
        int count = 0;
        
        for (NSString *key in keyTypes) {
            
            count++;
            
            [sql appendString:key];
            
            [sql appendString:@" "];
            
            [sql appendString:[keyTypes valueForKey:key]];
            
            if (count != [keyTypes count]) {
                
                [sql appendString:@", "];
                
            }
            
        }
        
        [sql appendString:@")"];
        
        [_db executeUpdate:sql];
        
    }
    
}

/**
 *  拿数据库
 */
+ (FMDatabase *)getDB{
    
    
    return _db;
}


/**
 *  构建归档目录文件
 *
 *  @param archiveFileName 归档文件名称
 *
 *  @return 归档文件沙盒地址
 */
+(NSString*)buildArchivePath:(NSString*)archiveFileName{
    NSArray *arrayPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [arrayPath objectAtIndex:0];
    NSString *archivePath = [cachePath stringByAppendingPathComponent:@"Archives"];
    ////NSlog(@"%@",archivePath);
    BOOL isDir = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:archivePath isDirectory:&isDir])
    {
        [fileManager createDirectoryAtPath:archivePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [archivePath stringByAppendingPathComponent:archiveFileName];
}

/**
 *  移除所有归档数据
 */
+(BOOL)removeAllArchives{
    NSArray *arrayPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [arrayPath objectAtIndex:0];
    NSString *archivePath = [cachePath stringByAppendingPathComponent:@"Archives"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //直接移除整个Archive文件夹
    if([fileManager fileExistsAtPath:archivePath])
    {
        return [fileManager removeItemAtPath:archivePath error:nil];
    }
    else {
        return YES;
    };
    
    //    将Archive文件夹中的文件逐个移除
    //    NSArray *subPaths = [fileManager subpathsAtPath:archivePath];
    //    for (NSString *fileName in subPaths)
    //    {
    //        if([fileManager fileExistsAtPath:[archivePath stringByAppendingPathComponent:fileName]])
    //        {
    //            [fileManager removeItemAtPath:[archivePath stringByAppendingPathComponent:fileName] error:nil];
    //        }
    //    }
}

/**
 *  通过唯一标识key缓存数据
 *
 *  @param archiveData 要缓存的数据
 *  @param key         唯一标识key
 *
 *  @return 是否缓存成功
 */
+ (BOOL)saveDataWithData:(id)archiveData key:(NSString *)key{
    
    
    NSString *filePath = [self buildArchivePath:key];
    
    return [NSKeyedArchiver archiveRootObject:archiveData toFile:filePath];
}

/**
 *  通过唯一标识key获取数据
 *
 *  @param key 唯一标识key
 *
 *  @return 返回数据
 */
+ (id)getDataWithKey:(NSString *)key{
    
    return  [NSKeyedUnarchiver unarchiveObjectWithFile:[self buildArchivePath:key]];
}

/**
 *  通过唯一标识key删除数据
 *
 *  @param key 唯一标识key
 *
 *  @return 是否删除成功
 */
+ (BOOL)removeDataForKey:(NSString *)key{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *archivePath = [self buildArchivePath:key];
    if([fileManager fileExistsAtPath:archivePath])
    {
        return [fileManager removeItemAtPath:archivePath error:nil];
    }
    return YES;
}

/**
 *  清除登录信息
 */
+ (void)clearUserMessage{
    
    [self removeDataForKey:KEY_USERMESSAGE];
    [self removeDataForKey:LYUserLoginInfo];
}


@end
